<template>
  <div class="lessonPlanCriterion">
    <div v-if="listData" class="tags-box">
      <div
        v-if="
          listData.resList[programmeIndex].resList[classHourIndex].resTeaching
            .filesArr
        "
      >
        <div
          v-for="(item, index) in listData.resList[programmeIndex].resList[
            classHourIndex
          ].resTeaching.filesArr"
          :key="index"
          class="clearfix marginT10"
        >
          <div
            v-if="item.type === 'pdf'"
            class="fl line-height30"
            style="color: #1E87F0;"
          >{{ item.name }}</div>
          <el-button
            v-if="item.type === 'pdf'"
            class="fl marginL10"
            type="primary"
            size="small"
            @click="openFile(item)"
          >预览</el-button>
        </div>
      </div>

      <div class="title marginT30">教案标签</div>
      <div
        v-for="(item, index) in listData.resList[programmeIndex].resList[
          classHourIndex
        ].resTeaching.tagList"
        :key="index"
        class="marginT20"
      >
        <div style="display: inline-block; border: 1px solid #ccc;">
          <div class="tags-item">
            <div class="left">{{ item.tagName }}：</div>
            <div class="center">
              <el-tag
                v-for="(tag, inx) in item.tagsArr"
                :key="inx"
                closable
                style=" background-color: white; border-color: white;"
                @close="handleClose(tag, inx, index)"
              >{{ tag.tagsName }}</el-tag>
            </div>
            <div class="right">
              <el-button type="text" @click="open(item, index)">修改</el-button>
              <el-button type="text" @click="delTags(item, index)">删除</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="button-box">
        <el-button type="primary" size="medium" round @click="open('')">添加标签</el-button>
      </div>
    </div>

    <div class="button-box">
      <!-- <button class="default">保存</button> -->
      <button class="submit" @click="save">保存</button>
    </div>

    <tagsDialog
      v-if="dialogVisible"
      :list="dialogObj"
      :dialog-visible="dialogVisible"
      @Callback="dialogCallback"
    />
  </div>
</template>

<script>
import tagsDialog from './tagsDialog';
import { updateTags } from './util';
import { personPrepareLessonUpdate, saveResTeaching } from '@/api/content';
import { tagsObjSwitch, getTagsItems } from '@/utils/categoryOrTags';
export default {
  name: 'LessonPlanCriterion',
  components: {
    tagsDialog
  },
  props: ['list', 'option', 'programmeInx', 'classHourInx'],
  data () {
    return {
      listData: this.list,
      options: this.option,
      programmeIndex: this.programmeInx,
      classHourIndex: this.classHourInx,
      dialogVisible: false,
      tagsIndex: null,
      dialogObj: {
        GROWTH_CLASSIFY: null,
        STAGE: null,
        SUBJECT: null,
        DOWNSTATUS: null,
        keynote: null,
        abilityArr: null,
        tagList: null,
        isAdd: null
      }
    };
  },
  computed: {},
  watch: {
    programmeInx (newName, oldName) {
      this.programmeIndex = newName;
    },
    classHourInx (newName, oldName) {
      this.classHourIndex = newName;
    }
  },
  created () {
    console.log('options', this.options);
    console.log('lessonPlanCriterion', this.classHourIndex);
    console.log('this.listData:', this.listData);

    if (
      this.listData.resList[this.programmeIndex].resList[this.classHourIndex]
        .resTeaching.files
    ) {
      // 处理附件
      var files = JSON.parse(
        this.listData.resList[this.programmeIndex].resList[this.classHourIndex]
          .resTeaching.files
      );
      var newArr = [];
      for (var i in files.module) {
        var index = files.module[i].lastIndexOf('\/');
        var inx = files.module[i].lastIndexOf('.');
        var name = files.module[i].substring(index + 1, files.module[i].length);
        var type = files.module[i].substring(inx + 1, files.module[i].length);
        newArr.push({
          name: name,
          url: files.module[i],
          type: type
        });
      }
      this.listData.resList[this.programmeIndex].resList[
        this.classHourIndex
      ].resTeaching.filesArr = newArr;
    }

    this.dialogObj = {
      GROWTH_CLASSIFY: this.listData.GROWTH_CLASSIFY,
      STAGE: this.listData.STAGE,
      SUBJECT: this.listData.SUBJECT,
      DOWNSTATUS: true
    };
    console.log(this.dialogObj);
    var obj = this.listData.resList[this.programmeIndex].resList[
      this.classHourIndex
    ].resTeaching.tagList;

    for (var i in obj) {
      if (JSON.stringify(obj[i].tags) !== '{}') {
        obj[i].tagsArr = tagsObjSwitch(obj[i].tags);
      } else {
        obj[i].tagsArr = [];
      }
    }
    console.log(obj);
    this.listData.resList[this.programmeIndex].resList[
      this.classHourIndex
    ].resTeaching.tagList = obj;
  },
  methods: {
    openFile (item) {
      // url 为线上地址
      // var docx = 'http://www.xdocin.com/demo/demo.docx';
      var fileUrl = item.url;
      if (!/\.(VIDEO|video|OTHER|other)$/.test(item.type)) {
        // window.open(
        //   'http://view.xdocin.com/xdoc?_xdoc=' + docx,
        //   '_blank'
        // );
        // 不是 VIDEO | OTHER 格式
        window.open(fileUrl, '_blank');
        return false;
      } else {
        this.$message('文件格式有误');
      }
    },
    open (items, index) {
      console.log('options:', this.options.category);
      this.tagsIndex = index || '';
      this.dialogObj.keynote = items.tagId || '';
      var key = [];
      if (JSON.stringify(items.tags) !== '{}') {
        for (var i in items.tags) {
          key.push(i);
        }
      }
      this.dialogObj.isAdd = !items;
      this.dialogObj.abilityArr = key;
      this.dialogObj.tagList = this.listData.resList[
        this.programmeIndex
      ].resList[this.classHourIndex].resTeaching.tagList;
      this.dialogVisible = true;
    },
    delTags (item, index) {
      const msg = '确认是否删除该标签！';
      this.$confirm(msg, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.listData.resList[this.programmeIndex].resList[
            this.classHourIndex
          ].resTeaching.tagList.splice(index, 1);

          console.log(
            this.listData.resList[this.programmeIndex].resList[
              this.classHourIndex
            ].resTeaching.tagList
          );
        })
        .catch(() => {
          // 取消操作
          console.log('cancel');
        });
    },
    handleClose (tag, inx, index) {
      console.log(tag, inx, index);
      // delete this.listData.resList[0].resList[this.classHourIndex].resTeaching.tagList[index].tags[inx];

      // console.log(this.listData.resList[0].resList[this.classHourIndex].resTeaching.tagList[index]);

      var obj = this.listData.resList[this.programmeIndex].resList[
        this.classHourIndex
      ].resTeaching.tagList;
      for (var i in obj) {
        if (this.checkArr(obj[i].tagsArr)) {
          for (var j in obj[i].tagsArr) {
            console.log(obj[i].tagsArr[j].tagsId);

            if (obj[i].tagsArr[j].tagsId === tag.tagsId) {
              obj[i].tagsArr.splice(j, 1);
            }
            // this.listData.resList[0].resList[this.classHourIndex - 1].resTeaching.tagList[i].tagsArr.splice(j, 1);
          }
        }
      }

      // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    // 编辑教案
    save () {
      var _this = this;
      this.saveTags().then(() => {
        console.log('saveTags:', _this.listData);
        var resTeachingBox =
          _this.listData.resList[_this.programmeIndex].resList[
          _this.classHourIndex
          ];

        console.log('resTeachingBox：', resTeachingBox.resTeaching.tagList);

        var keyPointTagList = []; // 重难点
        var improvementTagList = []; // 能力提升点
        resTeachingBox.resTeaching.tagList.map(item => {
          keyPointTagList.push({
            id: item.tagId,
            name: item.tagName
          });

          if (this.checkArr(item.tagsArr)) {
            item.tagsArr.map(tagsItem => {
              improvementTagList.push({
                id: tagsItem.tagsId,
                name: tagsItem.tagsName
              });
            });
          }
        });

        console.log('keyPointTagList:', keyPointTagList);
        console.log('improvementTagList:', improvementTagList);
        var data = {
          contentModule: JSON.stringify(
            resTeachingBox.resTeaching.templateContentVOList
          ),
          editModel: resTeachingBox.resTeaching.editModel,
          id: resTeachingBox.resTeaching.id,
          metadataThemeId: resTeachingBox.resTeaching.metadataThemeId,
          keyPointTagList: keyPointTagList,
          improvementTagList: improvementTagList,
          teachingDesignId: _this.listData.baseInfo.id,
          teachingDesignResId: resTeachingBox.id,
          typeEditTool: resTeachingBox.resTeaching.typeEditTool
        };
        console.log('data:', data);
        saveResTeaching(data).then(res => {
          this.$message({
            message: '保存成功',
            type: 'success'
          });
        });
      });

      // this.$emit('Callback', this.listData);
    },

    // 保存栏目标签-分类标签-简介
    saveTags () {
      var _this = this;
      return new Promise(function (resolve, reject) {
        //  _this.listData = updateTags(_this.listData, _this.options);

        console.log(' _this.listData:', _this.listData);
        // 分类标签
        var category = getTagsItems(_this.listData.categorySelect, _this.options.category);
        // console.log('分类标签：', category);
        var categoryArr = [];
        category.map(item => {
          categoryArr.push({
            id: item.tagsId,
            name: item.tagsName
          });
        });

        // 栏目标签
        var colTag = getTagsItems(_this.listData.contentSelect, _this.options.content);
        console.log('栏目标签：', colTag);
        var colTagArr = [];
        colTag.map(item => {
          colTagArr.push({
            id: item.tagsId,
            name: item.tagsName
          });
        });

        var tagsData = {
          categoryTag: categoryArr,
          columnTag: colTagArr,
          id: _this.listData.baseInfo.id,
          profiles: _this.listData.baseInfo.profiles
        };
        personPrepareLessonUpdate(tagsData).then(res => {
          resolve();
        });
      });
    },
    newContent (val) {
      // console.log('val:', val);
      // this.ruleForm.atvDescribe = val;
    },

    dialogCallback (obj) {
      // console.log('dialogCallback:', obj);
      this.dialogVisible = obj.dialogVisible;
      var _this = this;
      var abilityObj = {};
      if (this.checkArr(obj.ability)) {
        for (var i in obj.ability) {
          abilityObj[obj.ability[i].tagsId] = obj.ability[i].tagsName;
        }
      }

      if (this.checkArr(obj.keynote)) {
        var tagsObj = {
          tagId: obj.keynote[0].tagsId,
          tagName: obj.keynote[0].tagsName,
          tags: abilityObj,
          tagsArr: obj.ability
        };

        if (obj.isAdd) {
          _this.listData.resList[_this.programmeIndex].resList[
            _this.classHourIndex
          ].resTeaching.tagList.push(tagsObj);
        } else {
          _this.listData.resList[_this.programmeIndex].resList[
            _this.classHourIndex
          ].resTeaching.tagList.map((item, index) => {
            if (item.tagId === obj.keynote[0].tagsId) {
              _this.listData.resList[_this.programmeIndex].resList[
                _this.classHourIndex
              ].resTeaching.tagList[index] = tagsObj;
            }
          });
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.el-button + .el-button {
  margin-left: 20px;
}
.button-box {
  margin-top: 24px;

  .default {
    width: 94px;
    height: 40px;
    background: rgba(255, 255, 255, 1);
    border-radius: 4px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    margin-right: 30px;
    cursor: pointer;
  }
  .submit {
    width: 128px;
    height: 40px;
    border: none;
    background: rgba(84, 184, 123, 1);
    border-radius: 4px;

    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(255, 255, 255, 1);
    line-height: 24px;
    cursor: pointer;
  }
}

.tags-box {
  .tags-item {
    display: flex;
    padding-left: 15px;
    align-items: center;

    .left {
      width: 120px;
    }
    .center {
      flex: 1;
    }
    .right {
      width: 110px;
      box-sizing: content-box;
      padding-left: 30px;
    }
  }
}
</style>
